# -*- coding: utf-8 -*-
#

#import logging
#import logging.config
from service import Service
from servicepool import ServicePool
from servicemanager import ServiceManager

from sippeer.plugin.serviceplugin.servicemodule import *
from sippeer.utils.logutil import logger

import thread
import sys

#logging.config.fileConfig("../config/logging.conf")
#logger = logging.getLogger("ServiceFactory")

class ServiceFactory:
    """
    Factory to create running service and add into servicepool.
    """
    
    
    def __init__(self):
         """
         """
         
    def createServiceByName(self, service_name):
        """
        First, find the service in the service pool.
        Second, if found, return the running service.
                else, create running service using service manager
        
        using reflect mechanism to create class and class instance dynamically. 
        """
        
        if service_name == None or service_name == "":
            logger.error("ServiceFactory::createServiceByName(): service name can not be NULL")
            return None
        pool = ServicePool.getInstance()
        if pool == None:
            logger.error("ServiceFactory::createServiceByName(): Can not get service pool instance")
            return None
        if pool.findRunningService(service_name):
            logger.debug("ServiceFactory::createServiceByName(): Get running service by name successfully")
            return pool.getServiceByName(service_name)
        else:
            manager = ServiceManager.getInstance()
            if manager == None:
                logger.error("ServiceFactory::createServiceByName(): Can not get service manager instance")
                return None
            if manager.findService(service_name):
                logger.debug("ServiceFactory::createServiceByName(): No running service by name " + service_name + " , create running service")
                service_class_name = manager.getService(service_name)
                
                ################################################
                #  Generate class using class name and import ##
                #  Class name: serivce name + "Service"       ##
                #  Import module path: lowercase of class name##
                ################################################
                
                path = "sippeer.plugin.serviceplugin"
                __import__(path)
                m = sys.modules[path]
                logger.debug("ServiceFactory::createServiceByName(): Loaded module path 1:  " + str(m))
                
                module = getattr(m, service_class_name.lower())
                logger.debug("ServiceFactory::createServiceByName(): Loaded module path 2: " + str(module))
                
                ModuleClass = getattr(module, service_class_name)
    
                logger.debug("ServiceFactory::createServiceByName(): Loaded module service name: " + ModuleClass.__name__)
                logger.debug("ServiceFactory::createServiceByName(): Module type: " + str(type(ModuleClass)))
                
                if issubclass(ModuleClass, Service):
                    logger.debug("ServiceFactory::createServiceByName(): create running service successfully") 
                    service_instance = ModuleClass()
                    
                    if service_instance == None:
                        logger.error("ServiceFactory::createServiceByName(): create running service failed, return none")
                        return None
                    
                    service_instance.testImport()
                    
                    lock = thread.allocate_lock()
                    lock.acquire()
                    pool.addRunningServive(service_instance)
                    lock.release()
                    
                    return service_instance
                else:
                    logger.error("ServiceFactory::createServiceByName(): module class error, maybe not inherit from Service")
                    return None
                
            else:
                logger.error("ServiceFactory::createServiceByName(): the service is not existed, please check the manager")
                return None
            
            
    
        
    